<script setup lang="ts">
import { ref, watch } from "vue"
import { Modal } from "../modal"
import { Tag, Textarea } from "ant-design-vue"
import { ChangeEvent } from "ant-design-vue/es/_util/EventInterface"
const model = defineModel<string[]>()
const pasteValue = ref<string[]>([])
const showDialog = ref(false)

// 使用model的值初始化pasteValue
watch(
  ()=>showDialog.value,
  (val) => {
    if (val) {
      pasteValue.value = model.value || []
    }
  },
  { immediate: true }
)

function onSubmitValue() {
  showDialog.value = false
  model.value = pasteValue.value
}

function onTextAreaChange(e: ChangeEvent) {
  if (e.target?.value) {
    pasteValue.value = e.target.value.trim().replace(/\n+/g, " ").split(" ")
  } else {
    pasteValue.value = []
  }
}

function onTagClose(item: number|string) {
  pasteValue.value = pasteValue.value.filter(el=>el!==item)
}
</script>
<template>
  <h-icon-copy
    class="pc-cursor-pointer pc-hover:shadow"
    @click.stop="showDialog = true"
  />
  <Modal
    v-model="showDialog"
    title="批量粘贴"
    :mask="true"
    @ok="onSubmitValue"
  >
    <div class="pc-flex pc-flex-col pc-gap-3">
      <div>{{ `项目总计：${pasteValue?.length || 0}` }}</div>
      <div
        class="pc-max-h-32 pc-min-h-16 pc-overflow-auto pc-rounded pc-border pc-border-dashed pc-p-1"
      >
        <Tag
          v-for="item in pasteValue"
          :key="item"
          closable
          @close="onTagClose(item)"
        >
          {{ item }}
        </Tag>
      </div>

      <Textarea
        :value="pasteValue.join(' ')"
        class="pc-max-h-32"
        auto-size
        placeholder="请将数据粘贴在这里"
        @change="onTextAreaChange"
      />
    </div>
  </Modal>
</template>
